var express = require('express');
var router = express.Router();
const db = require('../configs/db.config'); // 引入数据库连接配置文件


router.get('/user', function(req, res, next) {
 handle1(req,res)
});

function handle1(req,res) {
    try{
        const tableName = 'flag_table'; // 替换为你的表名

        // 查询表是否存在
        db.query(
            `SELECT * FROM information_schema.tables WHERE table_schema = 'blog' AND table_name = '${tableName}' LIMIT 1;`,
            (error, results, fields) => {
                if (error) throw error;
                // console.log('dfdfd',results)
                if (results.length === 0) {
                    // 表不存在，创建表
                    db.query(`CREATE TABLE ${tableName} (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))`,
                        (createError, createResults, createFields) => {
                            if (createError) throw createError;
                            insertInitialData(tableName,() => {
                                console.log('数据插入成功')
                            })
                            res.send('数据表创建成功');
                        });
                } else {
                    // 表存在，查询数据
                    db.query(`SELECT * FROM ${tableName}`, (selectError, selectResults, selectFields) => {
                        if (selectError) throw selectError;
                        res.json(selectResults);
                    });
                }
            }
        );


        /*let sql = 'select * from article'
        let result = ''
        db.query(sql,function (err,result) {
          if(err) {
            console.log('[SELECT ERROR]：', err.message);
            return
          }
          result = JSON.parse(JSON.stringify(result))
          // console.log('result',result)
          let data = {
            code: 200,
            msg: '请求成功',
            list: result
          }
          res.send(data);
        })*/

    }catch (e) {

    }
}
// 插入初始数据的函数
function insertInitialData(tableName, callback) {
  const dataToInsert = [
    {name: 'John Doe'},
    {name: 'Jane Smith'}
  ];

  let insertCounter = 0;

  dataToInsert.forEach(item => {
    db.query(`INSERT INTO ${tableName} SET ?`, item, (error, results, fields) => {
      if (error) throw error;
      insertCounter++;

      // 当所有数据都插入完成后调用callback
      if(insertCounter === dataToInsert.length) {
        callback();
      }
    });
  });
}
module.exports = router;
